package a;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-26
 * Time: 22:20
 */
public class TcpEchoServe {
    private ServerSocket socket = null;
    public TcpEchoServe(int port) throws IOException {
        socket =new ServerSocket(port) ;
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {
            Socket clientSocket = socket.accept();
            //通过这个方法来处理一个连接
            processConnection(clientSocket);

        }
    }


    private void processConnection(Socket clientSocket) {
        //1.打印一个日志,告知有客户端连上了
        System.out.printf("[%s :%d] 客户端上线!\n",
                clientSocket.getInetAddress(),
                clientSocket.getPort());
        //2.从Socket中获得流对象,;来进一步的进行后续操作
        try(InputStream inputStream =clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            // 3. 也搞一个循环. 针对每个连接, 客户端都可能会发来多个请求, 服务器也就需要返回多个响应了.
            while(true){
                //3.1 读取请求并解析
                if(!scanner.hasNext()){
                    //如果发现后续没数据了,此时说明TCP的连接是已经断开了的
                    System.out.printf("[%s,%d] 客户端下线!\n" , clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //3,2 根据请求计算响应
                String response = process(request);
                //3.3 把响应写回给客户端
                outputStream.write(response.getBytes(),0,response.getBytes().length);
                //3.4 服务器打印日志
                System.out.printf("[%s : %d] res= %s, ques= %s\n",
                        clientSocket.getInetAddress(),clientSocket.getPort(),request,response);


            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //根据请求计算响应
    //由于是回显服务器,直接把请求作为响应返回回去
    private String process(String request) {
        //给响应这里后面加上一个换行符.使客户端读取响应的时候,也有明确的分隔符.

        return request+ "\n" ;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServe tcpEchoServe = new TcpEchoServe(9091);
        tcpEchoServe.start();

    }
}
